package com.outsider.util;

import java.util.HashMap;
import java.util.Random;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.outsider.news.dao.Acfun;



public class AcfunUtil {
    public static final String NEWS_URL="http://www.acfun.tv/a/ac";
    private static final String GAME_NEWS_URL="http://api.aixifan.com/searches/channel?channelIds=164&pageNo=1&pageSize=20&sort=4";
    private static final String GENERAL_NEWS_URL="http://api.aixifan.com/searches/channel?channelIds=110&pageNo=1&pageSize=20&sort=4";
    private static final HashMap<String , String> header=new HashMap<>();
    static{
    	header.put("deviceType", "1");
    }
    
    public static void updateLatestNews(){
    	Acfun.dao.deleteAll();
    	OkHttp3 okHttp3=OkHttp3.getInstance();
    	//游戏区新闻
    	JSONObject json=JSONObject.parseObject(okHttp3.getWithHeader(GAME_NEWS_URL, header));
    	decodeJSONAndSave(json);
    	JSONObject json1=JSONObject.parseObject(okHttp3.getWithHeader(GENERAL_NEWS_URL, header));
    	decodeJSONAndSave(json1);
    	Logger.getLogger("").info("Update acfun News Complete");
    	
    }

	private static void decodeJSONAndSave(JSONObject json) {
		if (json.getInteger("code")==200){
    		JSONArray list=json.getJSONObject("data").getJSONArray("list");
    		for (int i=0;i<list.size();i++){
    			JSONObject news=list.getJSONObject(i);
    			Acfun acfun=new Acfun();
    			acfun.setID(news.getInteger("contentId"));
    			acfun.setTitle(news.getString("title"));
    			JSONArray tag=(null!=news.getJSONArray("tags")?news.getJSONArray("tags"):null);
    			if (tag!=null){
    				StringBuilder sb=new StringBuilder();
    				for (int j=0;j<Integer.min(Const.TAGS_MAX_SIZE, tag.size());j++)
    					sb.append(tag.get(j)+" ");
    				acfun.setTags(sb.toString().trim());
    			}
    			acfun.save();
    		}
    	}
    	else{
    	   Logger.getLogger("").info("Acfun Util Error "+json.toString());
    	}
	}
    
    public static String getRandomPic(){
    	return Const.SERVER_IP+"/acfun/"+new Random().nextInt(41)+".gif"; 
    }
    
    public static Runnable getAcfunTask(){
    	Runnable task=new Runnable() {
			public void run() {
				AcfunUtil.updateLatestNews();
			}
		};
		return task;
    }
    public static void main(String args[]){
    	updateLatestNews();
    }
}
